<?php

namespace app\admin\controller\shop\notify;

use app\admin\controller\shop\Base;
use app\shop\library\ShopLogHelper;
use app\shop\service\NotifyService;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use Throwable;

/**
 * 消息通知管理
 */
class Notify extends Base
{
    /**
     * Notify模型对象
     * @var object
     * @phpstan-var \app\admin\model\shop\notify\Notify
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id'];

    protected array $withJoinTable = [];

    protected array $noNeedLogin = ['checkNotify'];

    protected array $noNeedPermission = ['read', 'batchRead', 'checkNotify'];

    protected string|array $quickSearchField = ['message'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\shop\notify\Notify();
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();

        $query = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias);

        foreach ($where as $key => $item) {
            list($field, $op, $value) = $item;
            if ($field == 'notify.status') {
                if ($value == 0) {
                    $query->whereRaw("NOT FIND_IN_SET({$this->auth->id}, `reader_id`)");
                }
                if ($value == 1) {
                    $query->whereFindInSet('reader_id', $this->auth->id);
                }
                unset($where[$key]);
            }
        }

        $res = $query->where($where)
            ->whereFindInSet('receiver_id', $this->auth->id)
            ->order($order)
            ->append(['status'])
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 读取消息
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function read(): void
    {
        $id      = $this->request->post('id');
        $adminId = $this->auth->id;
        $records = $this->model->whereIn('id', $id)->select();

        $updateData = [];
        foreach ($records as $record) {
            $readerIds = array_filter(explode(',', $record->reader_id));
            if (in_array($this->auth->id, $readerIds)) {
                continue;
            } else {
                $readerIds[]       = $adminId;
                $record->reader_id = implode(',', $readerIds);

                $updateData[] = [
                    'id'        => $record->id,
                    'reader_id' => $record->reader_id,
                ];
            }
        }

        $this->model->saveAll($updateData);

        $notifyService = new NotifyService();
        $notifyService->read($adminId, $id);

        $this->success();
    }

    /*
     * 检测是否有消息通知权限
     */
    public function checkNotify(): void
    {
        try {
            $check = $this->auth->check('shop/notify/notify');
        } catch (\Throwable $e) {
            ShopLogHelper::error('管理员消息通知权限检测失败', [], $e);
            $check = false;
        }

        $this->success('', [
            'check' => $check
        ]);
    }
}